package com.haiyi.software.app;

import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.haiyi.software.app.basic.FragmentBasicVPFriends;
import com.haiyi.software.entity.UserFriend;
import com.haiyi.software.tools.MyTools;
import com.haiyi.software.xmpp.event.XMPPConnectionState;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListDelegate;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshListView.PullToRefreshListAdapter;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

//FragmentVPFriends
public class FragmentVPBasic extends FragmentBasicVPFriends implements
		PullToRefreshListDelegate {

	private final String TAG = "FragmentVPBasic";
	protected View thisView;
	protected PullToRefreshListView mPullRefreshListView;
	private DisplayImageOptions options;
	protected ImageLoader imageLoader;
	private MyTools tools = MyTools.getInstance();

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		initComp();

		return thisView;
	}

	private void initComp() {

		// TODO 自动生成的方法存根
		// 图片控件
		imageLoader = ImageLoader.getInstance();
		options = new DisplayImageOptions.Builder()
				.imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
				.showImageOnLoading(R.drawable.ic_launcher)
				.showImageForEmptyUri(R.drawable.ic_launcher)
				.showImageOnFail(R.drawable.ic_launcher).cacheInMemory(true)
				.cacheOnDisc(true).considerExifParams(true)
				.displayer(new RoundedBitmapDisplayer(20)).build();

		mPullRefreshListView.setScrollingWhileRefreshingEnabled(false);

		// Set a listener to be invoked when the list should be refreshed.
		mPullRefreshListView
				.setOnRefreshListener(new OnRefreshListener<ListView>() {

					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {
						String label = DateUtils.formatDateTime(
								thisView.getContext(),
								System.currentTimeMillis(),
								DateUtils.FORMAT_SHOW_TIME
										| DateUtils.FORMAT_SHOW_DATE
										| DateUtils.FORMAT_ABBREV_ALL);
						// Update the LastUpdatedLabel
						refreshView.getLoadingLayoutProxy()
								.setLastUpdatedLabel(label);
						// Do work to refresh the list here.
						requestNetworkData();
					}
				});

		// Add an end-of-list listener
		mPullRefreshListView
				.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

					@Override
					public void onLastItemVisible() {

						Toast.makeText(thisView.getContext(), "已经到底部了!",
								Toast.LENGTH_SHORT).show();
					}
				});

		mPullRefreshListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				@SuppressWarnings("unchecked")
				Map<String, Object> mapInfo = (Map<String, Object>) parent
						.getItemAtPosition(position);

				// TODO 自动生成的方法存根
				Intent chatIntent = new Intent(getActivity(), HiChat.class);

				UserFriend friend = new UserFriend();

				// 用户名
				friend.setUfName(mapInfo.get("uname").toString());

				String photoString = str_defaultPhoto;

				if (mapInfo.get("userimg") != null) {

					photoString = view.getResources().getString(R.string.URL)
							+ mapInfo.get("userimg").toString();

				}

				// 头像
				friend.setUfPhoto(photoString);

				// UID
				friend.setUfID(mapInfo.get("uid").toString());

				Bundle bundleUF = new Bundle();

				bundleUF.putSerializable("com.hichat.UserFriend", friend);

				chatIntent.putExtras(bundleUF);

				startActivity(chatIntent);

			}
		});

		requestNetworkData();
	}

	/*
	 * ViewHolder
	 */
	private static class ViewHolder {

		TextView textViewName;
		ImageView imageViewPhoto;
		TextView textViewKmTime;
		TextView textViewContent;
		TextView textViewSex;
		Button btnPhoto;
	}

	private String str_km_distance = "";

	@Override
	public View bindView(PullToRefreshListAdapter adapter, final int position,
			View convertView, ViewGroup parent) {
		// TODO 自动生成的方法存根
		ViewHolder viewHolder = null;

		if (convertView == null) {
			convertView = adapter.getLayoutInflater().inflate(
					R.layout.item_nearby, null);
			viewHolder = new ViewHolder();
			viewHolder.imageViewPhoto = (ImageView) convertView
					.findViewById(R.id.item_n_photo);
			viewHolder.textViewContent = (TextView) convertView
					.findViewById(R.id.item_n_content);
			viewHolder.textViewKmTime = (TextView) convertView
					.findViewById(R.id.item_n_km_time);
			viewHolder.textViewSex = (TextView) convertView
					.findViewById(R.id.item_n_sex);
			viewHolder.textViewName = (TextView) convertView
					.findViewById(R.id.item_n_name);
			viewHolder.btnPhoto = (Button) convertView
					.findViewById(R.id.item_n_btn);
			convertView.setTag(viewHolder);

		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}
		viewHolder.textViewName
				.setText(data.get(position).get("username") != null ? data
						.get(position).get("username").toString() : "");

		str_km_distance = data.get(position).get("juli") != null ? tools
				.beautifulDistance(data.get(position).get("juli").toString())
				: "0.00km";

		str_km_distance += " | ";

		str_km_distance += data.get(position).get("lastdatetime") != null ? tools
				.beautifulDateTime(data.get(position).get("lastdatetime")
						.toString()) : "";

		viewHolder.textViewKmTime.setText(str_km_distance);
		viewHolder.textViewContent
				.setText(data.get(position).get("spcontent") != null ? data
						.get(position).get("spcontent").toString() : "");

		viewHolder.textViewSex.setBackgroundResource(tools
				.getSexBackground(data.get(position).get("usex").toString()));

		viewHolder.textViewSex
				.setText(data.get(position).get("age").toString());

		viewHolder.textViewSex.setGravity(Gravity.CENTER_VERTICAL);
		viewHolder.textViewSex.setPadding(40, 2, 5, 0);

		imageLoader.displayImage(
				str_server
						+ (data.get(position).get("userimg") != null ? data
								.get(position).get("userimg").toString() : ""),
				viewHolder.imageViewPhoto, options);

		viewHolder.btnPhoto.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO 自动生成的方法存根
				Log.i("btnCLICK", data.get(position).get("uid").toString());

				Intent intent = new Intent();
				intent.setClass(getActivity(), ActivityPersonal.class);
				Bundle theUID = new Bundle();
				theUID.putString("uid", data.get(position).get("uid")
						.toString());
				intent.putExtras(theUID);
				startActivity(intent);
			}
		});

		// TODO 自动生成的方法存根
		return convertView;
	}

	@Override
	public void requestFinish() {
		mPullRefreshListView.setPullToRefreshListDelegate(this);
		mPullRefreshListView.setDataSource(data);
		mPullRefreshListView.setAdapter(null);
		mPullRefreshListView.getAdapterEx().notifyDataSetChanged();
		mPullRefreshListView.onRefreshComplete();

	}

	@Override
	protected void requestError() {
		// TODO 自动生成的方法存根

	}

	@Override
	public void XMPPConnectionStateListener(XMPPConnectionState args) {
		// TODO 自动生成的方法存根
		
	}

}
